import { generate } from '@/api/live/live';
import { ScriptType } from '@/enum/enums';
import { EventBus } from '@/event-bus.js';
// import { getUUID } from "@/utils/util";
export const smartReplyMatch = {
  data() {
    return {
    };
  },
  created() {

    // for (let index = 0; index < 3; index++) {
    //   this.userBarrageDataList.push({
    //     nickName: "user" + index,
    //     content: '进入直播间',
    //     timestamp: Date.now(),
    //     id: getUUID(),
    //     hasGen: false,
    //     hasReply: false
    //   });
    // }
    // this.matchUserEnterInterval = setInterval(() => {
    //   this.matchContent();
    // }, 2000);

    EventBus.$on("smartReplyMatchSendWebSocket", () => {
      if (this.smartReplySetting.open) {
        this.matchContent();
      }
    });
  },
  beforeDestroy() {
    EventBus.$off('smartReplyMatchSendWebSocket');
  },
  mounted() { },
  computed: {
    pageConfig() {
      return this.$store.state.page.config;
    },
    smartReplySetting() {
      return this.pageConfig.smartReplySetting;
    },
    keyWordContentList() {
      let list = [];
      const content = this.$store.state.page.keyWordContent;
      if (!content) {
        return list;
      }
      content.split('\n').filter(line => line.trim() !== '').map(line => {
        const lineItems = line.split('-----');
        if (lineItems.length >= 2) {
          list.push({
            keyWords: lineItems[0].split('|'),
            contents: lineItems[1].split('\\')
          });
        }
      });
      return list;
    },
  },
  methods: {
    matchContent() {
      //找到最新的弹幕
      const tempList = this.userBarrageDataList.filter(item => !item.hasReply);
      if (tempList.length == 0) {
        return;
      }
      let userBarrage = tempList[tempList.length - 1];

      const findMatchItem = this.keyWordContentList.find(item => {
        return item.keyWords.some(keyWord => {
          //如果包含了这个关键字 并且不能是屏蔽字
          if (this.keywordSetting.blockWords) {
            let blockWordList = this.keywordSetting.blockWords.split('\n');
            if (blockWordList.length > 0) {
              let findBlockWordItem = blockWordList
                .filter(blockWord => blockWord.trim() !== '')
                .find(blockWord => userBarrage.content.includes(blockWord));
              if (findBlockWordItem) {
                return false;
              }
            }
          }
          return userBarrage.content.includes(keyWord);
        });
      });
      if (findMatchItem) {
        return;
      }
      if (userBarrage) {
        //匹配到关键字 就要将这个人去除掉
        userBarrage.hasReply = true;
        userBarrage.hasGen = true;
        generate({
          userName: userBarrage.nickName,
          text: userBarrage.content,
          scriptType: ScriptType.SMART_REPLY.code,
        });
      }
    }
  }
}
